<?php

/**
 * This is the model class for table "{{category}}".
 *
 * The followings are the available columns in table '{{category}}':
 * @property integer $id
 * @property string $name
 * @property string $slug
 * @property string $title
 * @property string $meta_keyword
 * @property string $meta_description
 * @property string $meta_robots
 * @property string $meta_revisit_after
 * @property integer $left_id
 * @property integer $right_id
 * @property integer $level
 * @property integer $root
 * @property integer $image_square
 * @property integer $image_thumbnail
 * @property integer $image_small
 * @property integer $image_crop
 * @property integer $image_medium
 * @property integer $image_large
 * @property integer $num_views
 * @property integer $is_active
 * @property string $created_date
 * @property string $modified_date
 * @property integer $user_id_create
 * @property string $language
 */
class Category extends CActiveRecord
{
    public $parent_id;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Category the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{category}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name, slug, parent_id', 'required'),
			array('name, slug', 'unique'),
			array('num_views, parent_id, is_active, user_id_create', 'numerical', 'integerOnly'=>true),
			array('name', 'length', 'max'=>255),
			array('slug', 'length', 'max'=>100),
			array('language', 'length', 'max'=>10),
			array('title, meta_keyword, meta_description, meta_robots, meta_revisit_after, created_date, modified_date, image_square, image_thumbnail, image_small, image_crop, image_medium, image_large', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, name, slug, title, meta_keyword, meta_description, meta_robots, meta_revisit_after, num_views, is_active, created_date, modified_date, user_id_create, language', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
        return array(
            'user'=>array(self::BELONGS_TO, 'user','user_id_create' ),
            'content'=>array(self::MANY_MANY, 'Content','{{content_category_assoc}}(content_id, category_id)' )
        );
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => t('ID','category'),
			'name' => t('Category Name','category'),
			'slug' => t('Slug','category'),
			'title' => t('Title','category'),
			'meta_keyword' => t('Keyword','category'),
			'meta_description' => t('Description','category'),
			'meta_robots' => t('Robots','category'),
			'meta_revisit_after' => t('Revisit After','category'),
			'left_id' => t('Left','category'),
			'right_id' => t('Right','category'),
			'level' => t('Level','category'),
			'root' => t('Root','category'),
			'num_views' => t('Num Views','category'),
			'is_active' => t('Status','category'),
			'created_date' => t('Created Date','category'),
			'modified_date' => t('Modified Date','category'),
			'user_id_create' => t('User Id Create','category'),
			'language' => t('Language','category'),
            'parent_id' => t('Parent','category'),

            'image_square' => t('Image Square','category'),
			'image_thumbnail' => t('Image Thumbnail','category'),
			'image_small' => t('Image Small','category'),
			'image_crop' => t('Image Crop','category'),
            'image_medium' => t('Image Medium','category'),
            'image_large' => t('Image','category'),
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

        $criteria->order = 'root,left_id,level';

		$criteria->compare('id',$this->id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('slug',$this->slug,true);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('meta_keyword',$this->meta_keyword,true);
		$criteria->compare('meta_description',$this->meta_description,true);
		$criteria->compare('meta_robots',$this->meta_robots,true);
		$criteria->compare('meta_revisit_after',$this->meta_revisit_after,true);
		$criteria->compare('left_id',$this->left_id);
		$criteria->compare('right_id',$this->right_id);
		$criteria->compare('level',$this->level);
		$criteria->compare('root',$this->root);
		$criteria->compare('num_views',$this->num_views);
		$criteria->compare('is_active',$this->filterStatus($this->is_active));
		$criteria->compare('created_date',$this->created_date,true);
		$criteria->compare('modified_date',$this->modified_date,true);
		$criteria->compare('user_id_create',$this->user_id_create);
		$criteria->compare('language',$this->language,true);

        $dependency = new CDbCacheDependency("SELECT MAX(created_date),MAX(modified_date) FROM {{category}}");
		return new CActiveDataProvider(self::model()->cache(settings()->get('system','cache_time'),$dependency,2), array(
			'criteria'=>$criteria,
            'pagination'=>array(
                        'pageSize'=>settings()->get('general','site_page_size')
            ),
		));
	}

    public function behaviors()
    {
        return array(
            'nestedSetBehavior'=>array(
                'class'=>'common.extensions.behaviors.tree.NestedSetBehavior',
                'hasManyRoots'=>true,
                'leftAttribute'=>'left_id',
                'rightAttribute'=>'right_id',
                'levelAttribute'=>'level'
            ),
        );
    }
    public function renderName($data,$row) {
        // $data ... the current row data
        // $row ... the row index
        $hyphen = '';
        for($i = 1;$i<$data['level'];$i++) {
            $hyphen = "—".$hyphen;
        }
        if($data['level']>1) {
            $hyphen = '|'.$hyphen;
        }
        return '<span style="color:#9A9A9A">'.$hyphen.'</span> <span rel="tooltip" data-original-title="'.t('Show details','category').'" style="color:#08c">'.ucfirst($data['name']).'</span><small> ( Slug :'.$data['slug'].' )</small>';
    }
    public function renderStatus($data,$row) {
        // $data ... the current row data
        // row ... the row index
        switch ($data['is_active']) {
            case 1 :
            $icon = "icon-ok";
            $tooltip = t('Deactive','fcms');
            break;
            case 0 :
            $icon = 'icon-remove';
            $tooltip = t('Active','fcms');
            break;
        }
        return '<div class="status-wap" id="status'.$data['id'].'">'.CHtml::link('<span class="'.$icon.'"></span>',url('/category/changeStatus/'.$data['id']),array(
            'onclick'=>"changeStatus('".url('/category/changeStatus/'.$data['id'])."',{ '".app()->request->csrfTokenName."' : '".csrfToken()."' },'#status".$data['id']."','".t('Do you want to change status ?','category')."');return false",
            'rel'=>'tooltip',
            'data-original-title'=>$tooltip
        )).'</div>';
    }
    public static function getDataCategory() {
        $tree = array();
        $cri = new CDbCriteria();
        $cri->order = 'root,left_id,level';
        $dependency = new CDbCacheDependency("SELECT MAX(created_date),MAX(modified_date) FROM {{category}}");
        $menu = Category::model()->cache(settings()->get('system','cache_time'),$dependency)->findAll($cri);
        foreach($menu as $m) {
            $name = ucfirst($m->name);
            for($i = 1;$i<$m->level;$i++) {
                $name = '—'.$name;
            }
            $tree[$m->id] = $name;
        }
        return $tree;
    }
    public static function getDescendants($parent){
        $arr = array();
        $dependency = new CDbCacheDependency("SELECT MAX(created_date),MAX(modified_date) FROM {{category}}");
        $pa = Category::model()->cache(settings()->get('system','cache_time'),$dependency)->findByPk($parent);
        $descendants = $pa->descendants()->findAll();
        foreach ($descendants as $de) {
            $arr[$de->id] = $de->name;
        }
        return $arr;
    }

    public function filterStatus($status){
        if(is_null($status)) return null;
        if(is_numeric($status)) return $status ; else return null;
    }

    public function beforeSave() {
        $current_user = getSession('current_user');
        if($this->getIsNewRecord()) {
            $this->created_date = new CDbExpression('UTC_TIMESTAMP()');
            $this->user_id_create = $current_user['id'];
            //$this->user_id_create = user()->getId();
        } else {
            $this->modified_date = new CDbExpression('UTC_TIMESTAMP()');
        }
        return parent::beforeSave();
    }
}